package com.runfast.waimai.service.impl;

import com.runfast.common.service.BaseService;
import com.runfast.common.web.entity.Result;
import com.runfast.waimai.dao.model.SysUserToken;
import com.runfast.waimai.dao.model.SysUserTokenExample;
import com.runfast.waimai.service.SysUserTokenService;
import com.runfast.waimai.utils.TokenGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SysUserTokenServiceImpl extends BaseService<SysUserToken,Long,SysUserTokenExample> implements SysUserTokenService {
    @Override
    public SysUserToken queryByToken(String token) {
        SysUserTokenExample example=new SysUserTokenExample();
        example.createCriteria().andTokenEqualTo(token);
        List<SysUserToken> list=mapper.selectByExample(example);
        SysUserToken sysUserToken=null;
        if(list !=null){
            if(list.size()>0){
                 sysUserToken=list.get(0);
            }
        }
        return sysUserToken;
    }

    //12小时后过期
    private final static int EXPIRE = 3600 * 12;


    @Override
    public Result createToken(long userId, Integer type) {
        //生成一个token
        String token = TokenGenerator.generateValue();
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
        //判断是否生成过token
        //SysUserToken tokenEntity = mapper.selectByPrimaryKey(userId);
        SysUserTokenExample example=new SysUserTokenExample();
        example.createCriteria().andUserIdEqualTo(userId).andUserTypeEqualTo(type);
        List<SysUserToken> list=mapper.selectByExample(example);
        SysUserToken tokenEntity =null;
        if(list != null){
            if(list.size()>0){
                tokenEntity=list.get(0);
            }
        }
        if(tokenEntity == null){
            tokenEntity = new SysUserToken();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            tokenEntity.setUserType(type);

            //保存token
            this.insert(tokenEntity);
        }else{
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            tokenEntity.setUserType(type);
            //更新token
            //this.updateById(tokenEntity);
            mapper.updateByPrimaryKeySelective(tokenEntity);
        }
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("token",token);
        map.put("expire",EXPIRE);
        Result r = Result.ok(null,map);

        return r;
    }
}